 
layui.define(['table','form','treeTable'], function(exports){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table
    ,setter = layui.setter
    ,admin = layui.admin
    ,treeTable = layui.treeTable
        ,dropdown = layui.dropdown;
    var renderTable;
    var field = '';
    var colsArr ;

    var tableTitle;
    var tableField; //表头字段
    var tableSearch = [];//全局搜索条件
    var tableHead;//表头字段


      

    
    // var currentMenuId = "5e68cc3e00ae426da7a7e8fcd07b1389";
    //
    // admin.req({
    //     url: setter.host+'/adminmanager/menu/menuListHead'
    //     ,type:'post'
    //     ,contentType: "application/json; charset=utf-8"
    //     ,data:'{menuId:"'+currentMenuId+'"}'
    //     ,done: function(res){
    //       //请求成功后
    //       if(res.status == setter.response.statusCode.status_Success){
    //         field = res.data;
    //
    //
    //       }else{
    //     	  window.location.href = setter.host+'/error/toNoPower?msg='+res.msg;
    //       }
    //     }
    // });

    tableRender();
      
    function tableRender(){
        colsArr = [
            {type: 'radio'},

            {field: 'id', title: '序号',width: 40,hide: true},
            {field: 'yicunzhao', title: '照片',width: 100,templet:function (rowData){
                console.log(rowData)
                    return `<img src='${rowData.yicunzhao}' width=100 height=100>`
                }},
            {field: 'name', title: '姓名',width: 80},
            {field: 'sex', title: '性别', align:'center'},
            {field: 'phone', title: '手机号码', align:'center'},
            {field: 'curr_stat', title: '当前状态', align:'center'},
            {field: 'entry_time', title: '入职时间',hide:true},
            {field: 'work_age', title: '工龄'},
            {field: 'department', title: '部门',align:'center'},
            {field: 'post', title: '岗位',align:'center'},
            {field: 'state', title: '状态',align:'center'},
            {field: 'nationality', title: '国籍',align:'center', hide:true},
            {field: 'nation', title: '民族',align:'center'},
            {field: 'politics', title: '政治面貌', align:'center'},
            {field: 'education', title: '学历', align:'center'},
            {field: 'school', title: '毕业院校', align:'center'},
            {field: 'code', title: '身份证号', align:'center'},
            {field: 'birth', title: '出生年月', align:'center'},
            {field: 'registered', title: '户口所在地', align:'center' },
            {field: 'address', title: '现住址', align:'center'},
            {field: 'number', title: '编号', align:'center'},
            {field: 'expire', title: '合同截止日期', align:'center'},
            {field: 'remarks', title: '备注', align:'center'},
            {field: 'gongzuozhaopian', title: '工作照', align:'center',templet:function (rowData){
                    console.log(rowData)
                    return `<img src='${rowData.gongzuozhaopian}' width=100 height=100>`
                }},
            {field: 'gerenjianli', title: '个人简历',width: 100,templet:function (rowData){
                    console.log(rowData)
                    return `<img src='${rowData.gerenjianli}' width=100 height=100>`
                }},
            {fixed: 'right',title: '工具',align: 'center' ,toolbar:function (){
                return ` <a class="layui-btn layui-btn-xs" lay-event="gongzuo">工作记录</a>
                            <a class="layui-btn layui-btn-xs" lay-event="gerenjianli">个人简历 <i class="layui-icon layui-icon-down"></i></a>`
                }}

        ];





        layui.each(colsArr,function(inx,val){
            console.log(val)
            field += val.hasOwnProperty('field')?val.field:'';
            field += ',';

            tableHead += val.hasOwnProperty('field')?val.field:'';
            tableHead += ',';
            tableTitle += val.hasOwnProperty('title')?(val.hide?'':val.title+','):',';
            tableField += val.hasOwnProperty('field')?(val.hide?'':val.field+','):',';
        })

        field = field.substring(field.indexOf(',')+1,field.length-2);
        loadTable(colsArr,field);
    }
    function loadTable(colsArr,field){
        var treeTableWhere = {};
        treeTableWhere.headField = field;
          
        renderTable = treeTable.render({
            elem: '#LAY-human-list',
            tree: {
            iconIndex: -1,  // 折叠图标显示在第几列
            idName: 'menuId'  // 自定义id字段的名称
            ,arrowType: 'arrow1' //箭头类型
            },
            limit: 15,
            limits:[15,30,50],
            id:"LAY-human-list",
            cols: colsArr,
            height: 'full-15',
            method:'post',
            contentType:"application/json; charset=utf-8",
            where:treeTableWhere,
            url: setter.host+'/human/menu/menuListBody'
        });

        //监听行工具事件
        treeTable.on('tool(LAY-human-list)', function(obj){
            //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                ,layEvent = obj.event; //获得 lay-event 对应的值

            console.log(data.id)
            layer.open({
                type: 1
                ,title: '工作记录'
                ,content: '<div class="layui-container" style="width: 98%"><table id="LAY-human-gzjl" lay-filter="LAY-human-gzjl" class=""></table></div>'
                ,shadeClose: true//开启遮罩关闭
                ,area: ['70%', '90%']
                ,maxmin: true
                ,btn: ['确定']
                ,success: function(layero, index){
                    //     var body=layer.getChildFrame('body',index);//少了这个是不能从父页面向子页面传值的
                    //     //获取子页面的元素，进行数据渲染
                    // console.log(body)
                    //     body.contents().find("#user_id").val(data.id);


                    table.render({
                        elem: '#LAY-human-gzjl'  // 弹出层表格id
                        ,url: setter.host + '/human/menu/getGongzuo' // 后端请求URL地址
                        ,method: 'post'
                        ,where: {'headField':'gz_start,gz_over,gz_bumen,gz_gangwei','user_id':data.id}
                        ,page: true
                        ,contentType:"application/json; charset=utf-8"
                        ,cols: [[
                            {field: 'gz_start', title: '开始日期',sort:true,align:'center'},
                            {field: 'gz_over', title: '结束日期',sort:true,align:'center'},
                            {field: 'gz_bumen', title: '部门',sort:true,align:'center',width: 100, sort: true,},
                            {field: 'gz_gangwei', title: '岗位',align:'center',sort:true,sort: true,width: 130,},
                        ]]
                    })
                    }
                ,yes: function(index, layero){
                    layer.close(index)
                }
            });

        });
    }
  
    $('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


  
    var active = {
        batchdel: function(){
            var checkData = renderTable.checkStatus()
                if(checkData.length === 0){
                    return layer.msg('请选择数据');
                }
            layer.prompt({
                formType: 1
                ,title: '敏感操作，请验证当前用户口令'
            }, function(value, index_prompt){
                var command = layui.sessionData('layuiSession').command;
                if(value == command){
                    layer.close(index_prompt);
                    layer.confirm('确定删除吗？', function(index_confirm) {
                        layer.close(index_confirm);
                        //因为是单选项，只能选择一个
                        if(checkData[0].hasOwnProperty('children')){
                            layer.confirm('该选择的删除数据有子菜单,确定都删除吗?', {icon: 3, title:'提示'}, function(index_del){
                                layer.close(index_del);
                                del(checkData[0].menuId,checkData[0].pId);
                            });
                        }else{
                            del(checkData[0].menuId,checkData[0].pId);
                        }
                    });
                }else{
                    layer.msg('口令错误');
                }  
            }); 
        }
        ,add: function(){
            // layer.open({
            //     type: 2
            //     ,title: '添加菜单'
            //     ,content: setter.host+'/human/menu/toInsert'
            //     ,area: ['720px', '590px']
            //     ,btn: ['确定', '取消']
            //     ,yes: function(index, layero){
            //         var iframeWindow = window['layui-layer-iframe'+ index]
            //         ,submitID = 'LAY-menu-add-submit'
            //         ,submit = layero.find('iframe').contents().find('#'+ submitID);
            //         //监听提交
            //         iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
            //             var indexLoad = layer.msg('添加菜单，请稍后', {
            //                 icon: 16
            //                 ,shade: 0.01
            //             });
            //             admin.req({
            //             url: setter.host+'/human/menu/insert'
            //             ,type:'post'
            //             ,dataType:'json'
            //             ,contentType: "application/json; charset=utf-8"
            //             ,data:JSON.stringify(data.field)
            //             ,done: function(res){
            //                 //请求成功后
            //                 if(res.status == setter.response.statusCode.status_Success){
            //                     if(data.field.menuId == '-1'){
            //                         loadTable(colsArr,field);
            //                         }else{
            //                             renderTable.refresh(data.field.menuId);
            //                     }
            //                 }
            //                 layer.close(index);
            //                 layer.close(indexLoad);
            //                 layer.msg(res.msg);
            //             }
            //             });
            //         });
            //         submit.trigger('click');
            //     }
            // });
            var obj = {};
            obj.bakUrl = setter.host+'/human/menu/toMenuList';
            obj.jsType = 'add';
            layui.common.postUrl(obj,setter.host+'/human/menu/toInsert');
        }
        ,edit: function(){
            var checkData = renderTable.checkStatus();
            if(checkData.length > 1){
                return layer.msg('只能选中编辑一行');
            }
            if(checkData.length ===0 ){
                return layer.msg('请选择一行数据进行编辑');
            }
            layer.open({
                type: 2
                ,title: '编辑菜单'
                ,content: setter.host+'/human/menu/toEdit'
                ,area: ['720px', '590px']
                ,btn: ['确定', '取消']
                ,success:function(editFrame,index){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,subBody = editFrame.find('iframe').contents();
                    var type = checkData[0].type;
                    subBody.find("#id").val(checkData[0].id)
                }
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = 'LAY-menu-edit-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                    //监听提交

                    console.log(iframeWindow,submitID,submit)
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                        console.log(JSON.stringify(data.field))
//                        data.field.menuId = checkData[0].menuId;
//                        data.field.pId = checkData[0].pId;
                        admin.req({
                            url: setter.host+'/human/menu/upUser'
                            ,type:'post'
                            ,dataType:'json'
                            ,contentType: "application/json; charset=utf-8"
                            ,data:JSON.stringify(data.field)
                            ,done: function(res){
                            //请求成功后
                            if(res.status == setter.response.statusCode.status_Success){
                                if(data.field.pId == '-1'||data.field.toChangePid=='-1'){
                                    loadTable(colsArr,field);
                                }else{
                                    renderTable.refresh(data.field.pId);
                                    //如果更新的菜单与当前修改的父菜单不一样，那么还需要刷新新修改后的菜单
                                    if(data.field.toChangePid !='' && data.field.pId != data.field.toChangePid){
                                    	renderTable.refresh(data.field.toChangePid);
                                    }
                                }
                            }
                            layer.close(index);
                            layer.msg(res.msg);
                            }
                        });
                    });  
                    submit.trigger('click');
                }
            });
        }
    }
    function del(menuId,pId){
        var indexLoad = layer.msg('删除菜单，请稍后', {
            icon: 16
            ,shade: 0.01
        });
        admin.req({
            url: setter.host+'/adminmanager/menu/batchdelMenu'
            ,type:'post'
            ,contentType: "application/json; charset=utf-8"
            ,data:'{"menuId":"'+menuId+'","pId":"'+pId+'"}'
            ,done: function(res){
                //请求成功后
                if(res.status == setter.response.statusCode.status_Success){
                        if(pId == '-1'){
                            loadTable(colsArr,field);
                        }else{
                            renderTable.refresh(pId);
                        }
                }
                layer.close(indexLoad);
                layer.msg(res.msg);
            }
        });
    }
    form.on('submit(LAY-human-normal-search)', function(data){
        var search = {};

        search.conditionField = data.field.whereKey;
        search.conditionValue = data.field.whereValue;
        search.conditionOption = 'like';
        tableSearch[0] = search;

//		tableSearch[data.field.whereKey] = data.field.whereValue;
        //执行重载
        // console.log(tableHead)
        // console.log(field)
        renderTable.reload({

            where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                search: tableSearch //查询字段
                ,headField:field //表头字段
                ,page:1//页码取第一页
            }
        });
    });
    //对外暴露的接口
      exports('select', {});
  });